package LinkedList;

public class 设计链表 {
}

class MyLinkedList {
    ListNode head;

    public MyLinkedList() {
    }

    public int get(int index) {
        if (head == null) return -1;
        if (index == 0) return head.val;
        else if (index > 0) {
            ListNode curr = head;
            for (int i = 0; i < index; i++) {
                if (curr.next != null) curr = curr.next;
                else return -1;
            }
            return curr.val;
        } else return -1;
    }

    public void addAtHead(int val) {
        addAtIndex(0, val);
    }

    public void addAtTail(int val) {
        ListNode curr = head;
        ListNode tail = new ListNode(val);
        if (curr == null) addAtIndex(0, val);
        else {
            while (curr.next != null) curr = curr.next;
            curr.next = tail;
        }
    }

    public void addAtIndex(int index, int val) {
        if (index == 0) {
            ListNode newHead = new ListNode(val);
            newHead.next = head;
            head = newHead;
        }
        ListNode curr = head;
        ListNode node = new ListNode(val);
        int i = 0;
        while (i < index - 1) {
            if (curr == null) break;
            if (curr.next != null) {
                curr = curr.next;
                i++;
            } else break;
        }
        if (i == index - 1 && curr != null) {
            node.next = curr.next;
            curr.next = node;
        }
    }

    public void deleteAtIndex(int index) {
        if (index == 0) head = head.next;
        ListNode curr = head;
        int i = 0;
        while (i < index - 1) {
            if (curr == null) break;
            if (curr.next != null) {
                curr = curr.next;
                i++;
            } else break;
        }
        if (i == index - 1 && curr.next != null) curr.next = curr.next.next;
    }
}
